/**
 *
 */
package com.dididoctor.patient.Activity.splash;

import android.content.Context;
import android.util.Log;

import com.dididoctor.patient.Activity.ConstantValue;
import com.dididoctor.patient.Activity.GlobalParams;
import com.dididoctor.patient.Bean.AppVersion;
import com.dididoctor.patient.Bean.DiaeasesLitapal;
import com.dididoctor.patient.Bean.Token;
import com.dididoctor.patient.Http.MyHttpResponseHandler;
import com.dididoctor.patient.MV.BasePresenter;
import com.dididoctor.patient.MV.BusinessClient;
import com.dididoctor.patient.MV.Response;
import com.dididoctor.patient.Ui.cityList.CityBean;
import com.dididoctor.patient.Utils.ABAppUtil;
import com.dididoctor.patient.Utils.LogUtil;
import com.dididoctor.patient.Utils.SharedPreferencesUtils;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @version 2.0
 * @类描述： 起始页
 * @项目名称：douDouTech
 * @类名称： SplashActivity
 * @包名称： com.doudoukeji.service.Activity.splash
 * @创建人：张强 boy
 * @创建时间：2016/3/7 16:40
 * @修改人：
 * @修改时间：2016/3/7 16:40
 * @修改备注： new parent class(用一句话描述修改了什么)
 */
public class SplashPresenter extends BasePresenter {

    private SplashView view = null;
    private static final String TAG = "LaunchActivity";
    private Context mcontext;

    //是否登录
    private boolean isLogin = false;
    //医院服务信息是否填完整
    private boolean isAll = false;
    //是否更新
    private boolean isUpdata = false;
    //是否显示数据同步进度条
    private boolean isShow = false;
    //同步数据失败
    private boolean isErrar = false;

    private AppVersion appVersionBean = null;

    public SplashPresenter(Context context, SplashView view) {
        super(context, view);
        this.view = view;
        this.mcontext = context;
    }

    /**
     * @param
     */
    public void launch() {
//        appVersion	String	是	APP版本号（后端判断传来本字段，端版本号低，则返回信息，如一致则不返回信息）
//        device	String	是	设备类型
//        disVersion	String	是	24种小病数据的版本号（后端判断传来本字段，端版本号低，则返回信息，如一致则不返回信息）
//        userId	String 	是	用户（用户手机号与用户都一致，则返回用户信息）
//        token	string	是
        final RequestParams params = new RequestParams();
        params.put("appVersion", ABAppUtil.getAppVersion(mcontext));
        params.put("device", "1");
        params.put("disVersion", Token.getDisVersion());
        params.put("token", Token.getToken());
        params.put("userId", Token.getId());


        BusinessClient.post(ConstantValue.splashUrl, params, new MyHttpResponseHandler() {

            @Override
            public void onStart() {
                super.onStart();
                String isFirst = SharedPreferencesUtils.getParam(mcontext, "isFirst", "-1");
                if (!isFirst.equals("0")) {
                    view.ShowSynchronousData();
                    isShow = true;
                }
            }

            @Override
            public void onMyResponse(Response response) {
                if ("1".equals(response.getStatus())) {
                    LogUtil.info(SplashPresenter.class, "启动的返回数据:" + response.getJson(),
                            ConstantValue.currentStage);


                    if (!response.isSucceed()) {
                        Log.i("CheckVersion", "检查新版本失败");
                        return;
                    }
                    //app更新版本号
                    String appVersion = response.getString("appVersion");
                    if (!"".equals(appVersion) && appVersion != null) {

                    }else{
                        appVersion = "0";
                    }

                    // "disVersion": 1,//24种小病
                    String disVersion = response.getString("disVersion");
                    if (!"".equals(disVersion) && disVersion != null) {
                    } else {
                        disVersion = "0";
                    }
//
                    ArrayList<CityBean> hotCityDatas = new ArrayList<CityBean>();
                    List<Map<String, String>> hotCityMaps = response.getListData("cityHot");
                    for (Map<String, String> map : hotCityMaps) {
                        CityBean cityBean = new CityBean();
                        cityBean.setCityCode(map.get("cityCode"));
                        cityBean.setCityName(map.get("cityName"));
                        hotCityDatas.add(cityBean);
                    }
                    GlobalParams.hotCityData = hotCityDatas;
                    // "userVersion": 1,//0-不登录自动登录
                    String userVersion = response.getString("userVersion");
                    if (!"".equals(userVersion) && userVersion != null) {

                    }else{
                        userVersion = "0";
                    }


                    //第一次进入显示数据同步信息 ，设置标记为0标示已经登录过了
                    //第二次进入有同步数据时打开同步服务器，直接进入主页
                    //如果有数据字典产生，则显示数据同步
                    if (!Token.getDisVersion().equals(disVersion)) {
                        //存数据库的医院信息
                        List<Map<String, String>> diseasesData = response.getListData("diseases");
                        setDiaeasesLitapal(diseasesData);
                    }

                    if ("1".equals(userVersion)) {
                        //存入文件的用户信息
                        Map<String, Object> userInfo = response.getMap("userInfo");
                        setUserInfoData(userInfo);
                    }


                    //版本判断，是否要更新版本
                    int NativeappVersion = ABAppUtil.getAppVersion(Token.getMcontext());
                    if ("1".equals(appVersion)) {
                        //版本信息表
                        Map<String, Object> appData = response.getMap("appData");
                        isUpdata = true;
                        appVersionBean = new AppVersion();

                        //                    "versionNo": "1",
                        //                            "versionName": "测试版本",
                        //                            "descr": "测试版本",
                        //                            "device": "0",
                        //                            "forceUpdate": "0",
                        //                            "path": ""
                        appVersionBean.setVersionNo((String) appData.get("versionNo"));
                        appVersionBean.setVersionName((String) appData.get("versionName")); // 0表示非必须，1表示必须
                        appVersionBean.setDescr((String) appData.get("descr"));
                        appVersionBean.setDevice((String) appData.get("device"));
                        appVersionBean.setForceUpdate((String) appData.get("forceUpdate"));
                        appVersionBean.setPath((String) appData.get("path"));
                        return;
                    }
                } else {
                    view.ErrorSynchronousData();
                    isErrar = true;
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (!isUpdata) {
                    String isFirst = SharedPreferencesUtils.getParam(mcontext, "isFirst", "0");
                    //第一次登录过则标记为1，跳过引导页到主界面或者登录页
                    if ("1".equals(isFirst)) {
                        if (!isErrar) {

                            if (isShow) {
                                view.DissSynchronousData();
                            }

                            if (isLogin) {
                                String read = SharedPreferencesUtils.getParam(context, "READ", "0");
                                if ("1".equals(read)) {
                                    view.intentMainActivity();
                                } else {
                                    view.initentDisclaimerActivity();
                                }

                            } else {
                                view.intentLoginActitity();
                            }
                        }

                    } else {
                        if (!isErrar) {
                            SharedPreferencesUtils.setParam(mcontext, "isFirst", "1");
//                            view.intentGuideActivity();
                            view.intentLoginActitity();
                            // 隐藏数据同步进度条
                            view.DissSynchronousData();
                        }
                    }
                } else {
                    view.tipUpdataDiolag(appVersionBean);
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                super.onFailure(i, headers, bytes, throwable);
                if (isShow) {
                    view.ErrorSynchronousData();
                    isErrar = true;
                }
            }
        });
    }

    /**
     * 设置登录信息
     */
    private void setUserInfoData(Map<String, Object> userInfo) {
//        "userId": "5",//用户
//                "phone": "13963941179",//用户手机号
//                "name": "139****1179",//用户名称没有用户名的情况下，用户名为手机号前三位＋＊＊＊＊＋后四位
//                "headPic":"头像"
//        "sex":"性别"
//        "birth":"出生日期"
//        "idNo":"身份证号"
//        "city":"城市"
//        "address":"详细地址"
//        "token": "afdsgjfkljgljeoirewl;gfdkasjkfj",//唯一识别码
//        “accId”:”云信ID”
//        “accPwd”:”登录token值”
        if (!isShow) {
            // 显示数据同步进度条
            view.ShowSynchronousData();
            isShow = true;
        }
        Token.setId((String) userInfo.get("userId"));
        Token.setPhone((String) userInfo.get("phone"));
        Token.setName((String) userInfo.get("name"));
        Token.setHeadPic((String) userInfo.get("headPic"));
        Token.setSex((String) userInfo.get("sex"));
        Token.setBirth((String) userInfo.get("birth"));
        Token.setIdNo((String) userInfo.get("idNo"));
        Token.setCity((String) userInfo.get("city"));
        Token.setAddress((String) userInfo.get("address"));
        Token.setToken((String) userInfo.get("token"));
        Token.setAccId((String) userInfo.get("accId"));
        Token.setAccPwd((String) userInfo.get("accPwd"));
        isLogin = true;
    }

    /**
     * 存入数据库的数据列表   医院信息数据字典
     *
     * @param list
     */
    public void setDiaeasesLitapal(List<Map<String, String>> list) {

        if (!isShow) {
            // 显示数据同步进度条
            view.ShowSynchronousData();
            isShow = true;
        }


        if (list != null && list.size() > 0) {
            DataSupport.deleteAll(DiaeasesLitapal.class);
            for (Map<String, String> map : list) {
                DiaeasesLitapal dicf = new DiaeasesLitapal();
//                "id": "1",   //医院
//                        "name":"青岛市立医院医院名称
//                "areaName": "市南区所在城市
//                "areaId": "0110" //地区
                dicf.setDisId(map.get("disId"));
                dicf.setName(map.get("name"));
//                dicf.saveThrows();
                dicf.save();
            }
            LogUtil.info("医院DicInFor表有" + DataSupport.count(DiaeasesLitapal.class) + "条数据====",
                    ConstantValue.currentStage);
        }

    }
}